package repository

import (
	"SE/model"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"time"
)

type CarRepository interface {
	// UserExists 检查用户名和电话是否已存在
	UserExists(carId, location string) bool
	// CreateUser 创建新用户
	CreateUser(car *model.CarP) error

	DeleteUser(id, pid int) (time.Time, error)
}

// carRepository 结构体实现了carRepository接口
type carRepository struct {
	db *gorm.DB
}

func (ca *carRepository) DeleteUser(id, pid int) (time.Time, error) {
	//TODO implement me
	var t time.Time
	sql1 := "UPDATE car_p set status = 1 WHERE id = ?"
	if err := ca.db.Exec(sql1, id).Error; err != nil {
		return t, err
	}
	sql2 := "UPDATE car_p SET out_time = ? WHERE id = ?"
	if err := ca.db.Exec(sql2, time.Now(), id).Error; err != nil {
		return t, err
	}
	var num int64
	sql3 := "SELECT car_num from p where id = ?"
	if err := ca.db.Raw(sql3, pid).Count(&num).Error; err != nil {
		return t, err
	}

	fmt.Print(num)
	sql4 := "UPDATE p SET car_num = ? WHERE id = ?"
	if err := ca.db.Exec(sql4, num-1, pid).Error; err != nil {
		return t, err
	}

	return t, nil
}

func NewCarRepository(db *gorm.DB) CarRepository {
	return &carRepository{db: db}
}

func (ca *carRepository) UserExists(carId, location string) bool {
	var carP model.CarP
	return ca.db.Where("car_id = ? AND location = ?", carId, location).First(&carP).Error == nil
}

func (ca *carRepository) CreateUser(car *model.CarP) error {
	//TODO implement me
	car.OutTime = time.Now()
	var count1, count2 int64
	sql := "SELECT COUNT(*) FROM car_p where p_id = ?"
	err := ca.db.Raw(sql, car.PId).Count(&count1).Error
	if err != nil {
		return err
	}
	sql2 := "SELECT total from p where id = ?"
	err = ca.db.Raw(sql2, car.PId).Count(&count2).Error
	if err != nil {
		return err
	}

	if count1 >= count2 {
		errs := errors.New("停车位不够")
		return errs
	}
	sql3 := "UPDATE p SET car_num = ? WHERE id = ?"
	err = ca.db.Exec(sql3, count1+1, car.PId).Error
	if err != nil {
		return err
	}
	sql4 := "INSERT INTO car_p (car_id, p_id, in_time, out_time, status,uid) VALUES (?, ?, ?, ?, ?, ?)"
	err = ca.db.Exec(sql4, car.CarId, car.PId, car.InTime, car.OutTime, car.Status, car.UId).Error
	if err != nil {
		return err
	}
	return nil
}
